# __init__.py
from nonebot import get_driver, require, logger, on_message
from nonebot.adapters.onebot.v11 import Bot, GroupMessageEvent
from .client import WSClient
from .config import Config, __plugin_meta__

# 导入定时任务模块
require("nonebot_plugin_apscheduler")
from nonebot_plugin_apscheduler import scheduler

# 初始化客户端实例
client = WSClient()

# 注册关闭钩子
driver = get_driver()
driver.on_shutdown(client.shutdown)

# 定时任务注册
@scheduler.scheduled_job(
    "interval", 
    seconds=5,
    id="ws_connect",
    max_instances=2,
    coalesce=True,
)
async def keep_connection():
    if not client.connected:
        await client.connect()

# 监听群消息事件
group_message_handler = on_message(priority=10, block=False)

@group_message_handler.handle()
async def handle_group_message(bot: Bot, event: GroupMessageEvent):
    # 检查是否是指定的监听群
    if not event.group_id in client.config.source_groups:
        return
    # 过滤掉机器人自己的消息
    if not event.user_id != int(bot.self_id):
        return

    processed_message = process_message_segments(event.message)
    # 过滤掉空消息
    if processed_message.strip():
        # 获取群名
        try:
            group_info = await bot.get_group_info(group_id=event.group_id)
            group_name = group_info.get("group_name", f"群{event.group_id}")
        except Exception as e:
            logger.warning(f"获取群名失败: {e}")
            group_name = f"群{event.group_id}"
        
        # 发送到WebSocket服务器
        await client.send_to_server({
            'type': 'group_to_server',
            'group_id': event.group_id,
            'user_id': event.user_id,
            'nickname': event.sender.nickname or str(event.user_id),
            'group_name': group_name,
            'message': processed_message
        })

def process_message_segments(message) -> str:
    """处理消息段，将不同类型的消息段转换为适合MC显示的文本"""
    result_parts = []
    
    for segment in message:
        segment_type = segment.type
        
        if segment_type == "text":
            # 纯文本直接添加
            text_content = segment.data.get("text", "").strip()
            if text_content:
                result_parts.append(text_content)
                
        elif segment_type == "face":
            # QQ表情转换为[表情]
            result_parts.append("[表情]")
            
        elif segment_type == "image":
            # 图片转换为[图片]
            result_parts.append("[图片]")
            
        elif segment_type == "at":
            # @某人
            qq_id = segment.data.get("qq", "")
            if qq_id == "all":
                result_parts.append("[@全体成员]")
            else:
                result_parts.append(f"[@{qq_id}]")
                
        elif segment_type == "record":
            # 语音转换为[语音]
            result_parts.append("[语音]")
            
        elif segment_type == "video":
            # 视频转换为[视频]
            result_parts.append("[视频]")
            
        elif segment_type == "share":
            # 链接分享
            title = segment.data.get("title", "")
            url = segment.data.get("url", "")
            if title:
                result_parts.append(f"[分享: {title}]")
            else:
                result_parts.append("[链接分享]")
                
        elif segment_type == "location":
            # 位置信息
            result_parts.append("[位置]")
            
        elif segment_type in ["rps", "dice"]:
            # 魔法表情
            result_parts.append(f"[{segment_type.upper()}]")
            
        elif segment_type == "shake":
            # 窗口抖动
            result_parts.append("[戳一戳]")
            
        elif segment_type == "poke":
            # 戳一戳
            poke_name = segment.data.get("name", "戳一戳")
            result_parts.append(f"[{poke_name}]")
            
        else:
            # 其他未知类型的消息段
            result_parts.append(f"[{segment_type}]")
    
    return " ".join(result_parts)

# 导出必要元素（NoneBot要求）
__all__ = ["__plugin_meta__", "Config", "client"]